<template>
<!--  模型详情界面-->
  <div class="total">
    <!--   spss结果展示-->
    <div class="spss">
      <!--     分析流程-->

      <div class="analyze_process">
        <div class="totaltitle">
          <div class="blue-rectangle"></div>
          <h1>基本信息</h1>
        </div>
        <div class="processcontent">
          <!--          <el-table :data="transformedData" style="width: 100%">-->
          <!--            <el-table-column prop="fieldName" label="字段名"></el-table-column>-->
          <!--            <el-table-column label="字段值">-->
          <!--              <template #default="{ row }">-->
          <!--                {{ row.fieldValue }}-->
          <!--              </template>-->
          <!--            </el-table-column>-->
          <!--          </el-table>-->

          <el-table :data="transformedData" style="width: 100%">
            <el-table-column prop="fieldName" label="字段名"></el-table-column>
            <el-table-column label="字段值">
              <template #default="{ row }">
                <template v-if="Array.isArray(row.fieldValue)">
                  <el-table
                    :data="row.fieldValue"
                    style="width: 100%"
                    :show-header="false"
                  >
                    <!--                    <el-table-column type="index" label="序号"></el-table-column>-->
                    <el-table-column
                      prop="param_name"
                      label="参数名"
                    ></el-table-column>
                    <el-table-column
                      prop="param_defaultValue"
                      label="默认值"
                    ></el-table-column>
                  </el-table>
                </template>
                <template v-else>
                  {{ row.fieldValue }}
                </template>
              </template>
            </el-table-column>
          </el-table>

          <div class="up2hv2img">
            <img
              style="width: 12.5em"
              src="../../assets/common-icons/暂无图片.png"
            />
          </div>
        </div>
      </div>

      <!--      参数说明-->
      <div class="analysis_steps">
        <div class="totaltitle totaltitle1">
          <div class="blue-rectangle"></div>

          <h1>参数说明</h1>
        </div>
        <div class="stepscontent">
          <div>
            <div
              v-for="(param, index) in tableData.model_ParaIntro"
              :key="param"
            >
              {{ index + 1 }}、{{ param.param_name }}：{{
                param.param_explain
              }}，单位：{{ sanitize(param.param_unit) }}
            </div>
          </div>
        </div>
      </div>

      <!--      历史计算-->
      <div class="historystatistics">
        <div class="totaltitle totaltitle1">
          <div class="blue-rectangle"></div>
          <h1>历史计算</h1>
        </div>
        <div class="conclusioncontent">
          <div class="tablespace">
            <div class="table2">
              <el-table
                :data="currentPageData"
                border
                style="width: 100%"
                max-height="550px"
                height="500px"
              >
                <!--                  <el-table-column  type="index" width="60"></el-table-column>-->
                <!--                  <el-table-column  prop="_id" label="ID" width=""></el-table-column>-->
                <el-table-column prop="" label="序号">
                  <template #default="scope">
                    {{ scope.$index + 1 }}
                  </template>
                </el-table-column>

                <el-table-column
                  prop="model_name"
                  label="模型名称"
                ></el-table-column>
                <el-table-column
                  prop="model_type"
                  label="模型类别"
                ></el-table-column>
                <el-table-column prop="GroupsOrOne" label="计算类型"></el-table-column>
                <el-table-column
                  prop="save_time"
                  label="保存时间"
                ></el-table-column>
                <el-table-column label="操作">
                  <template #default="scope">
                    <!--            <p>{{ scope.row}}</p>-->
                    <el-button
                      class="tablebutton"
                      @click="handleEdit(scope.row)"
                      >详情
                      <el-icon>
                        <edit></edit>
                      </el-icon>
                    </el-button>

                    <el-button
                      class="tablebutton"
                      @click="showDeleteDialog(scope.row._id)"
                      >删除
                      <el-icon>
                        <remove></remove>
                      </el-icon>
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>

              <!--  页尾 开始-->
              <div class="footpage" style="">
                <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="pageNum"
                  :page-size="pageSize"
                  :page-sizes="[2, 5, 10, 20]"
                  :small="small"
                  :disabled="disabled"
                  :background="background"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                >
                </el-pagination>
              </div>
              <!--  页尾结束-->

              <!--    新加的确定删除的弹窗-->
              <el-dialog
                style="border-radius: 0.938em"
                v-model="deleteDialogVisible"
                title="确认删除"
                width="30%"
              >
                <p>确定要删除此次计算结果吗？</p>
                <template #footer>
                  <span class="dialog-footer">
                    <el-button
                      style="border-radius: 4px"
                      @click="handleDelete"
                      type="danger"
                      >确定</el-button
                    >
                    <el-button style="border-radius: 4px" @click="cancelDelete"
                      >取消</el-button
                    >
                  </span>
                </template>
              </el-dialog>
            </div>
          </div>
        </div>


      </div>


      <div class="attached_file">
        <div class="totaltitle">
          <div class="blue-rectangle"></div>
          <h1>附件文件</h1>
        </div>
        <div class="conclusioncontent">
          <div class="attachment">
            <div class="downloadcode">
              <h1>代码</h1>
              <div class="atimg">
                <img src="../../assets/model-detail-icons/代码.png" alt="" />
              </div>
              <el-button class="backbutton" @click="download_code" style="">下载代码</el-button>
            </div>

            <div class="downloadattachment">
              <h1>附件</h1>
              <div class="atimg">
                <img
                  src="../../assets/model-detail-icons/附件文件夹.png"
                  alt=""
                />
              </div>
              <el-button class="backbutton" style="" @click="download_attachment">下载附件</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="functionbutton">
      <!-- 其它按钮和功能 -->
      <!--     <el-button type="info" @click="dialogFormVisible = false; load">取消</el-button>-->
      <!--     <el-button type="primary" @click="save">确认</el-button>-->
      <el-button style="" type="" @click="goBack">返回</el-button>
      <!-- 添加返回按钮 -->
      <el-button style="" @click="useParam">使用</el-button>
    </div>
  </div>
</template>

<script>
import router from "@/router";

// import historyCaculate from "@/data1/historyCaculate";
import modelListData from "@/data1/modelListData";
// import DissolutionRateChart from "@/components/dissolutionratechart/DissolutionRateChart";
// import { saveAs } from 'file-saver';
export default {
  name: "ModelDetail",
  props: {
    baseUrl: {
      type: String,
    },
    row: {
      type: Object,
      default: function () {
        return {};
      },
    },
    selected_model_id: {
      type: String,
    },
  },
  setup() {},
  components: {
    // DissolutionRateChart,
  },

  data() {
    return {
      downloadFileName:{},
      pageNum: 1,
      pageSize: 10,
      total: 0,
      modelData: modelListData,
      historyCaculate: [],
      dialogFormVisible: true,
      deleteDialogVisible: false,
      form: {},
      deleteid: "",
      tableData: {},
      config: {
        model: "单一容器模型",
        parameter:
          "向后预测单位:{12]}:季节性周期长度:{12];是否参数自动寻优:{是}\n",
        variate: "时间序列变量:{年度销量}\n",
      },
      transformedData: [],
      currentPageData: [],
      username: "",
    };
  },
  created() {
    if (this.selected_model_id !== -1) {
      localStorage.setItem("selected_model_id", this.selected_model_id);
    }
  },
  mounted() {


    this.username = localStorage.getItem("username");
    let _id = null;
    if (this.selected_model_id !== -1) {
      _id = this.selected_model_id;
    } else {
      _id = localStorage.getItem("selected_model_id");
    }
    if (_id == null) {
      this.$message.error("获取模型id错误");
      return;
    }
    this.request
      .post("/model/checkModelByid", {
        id: _id,
        username: this.username,
      })
      .then((res) => {
        if (res.code === 200) {
          console.log(res);
          this.tableData = res.data;
          // console.log(this.tableData._id)
          this.transformedData = this.transformData(res.data);
          this.load(() => {
            // console.log("打印这个模型的历史计算\n"+this.historyCaculate)
            this.historyCaculate = this.handleModelNameFilter();
            this.currentPageData = this.Show_CurrentPage(this.historyCaculate);
          });
          this.getFileName()
        } else {
          this.$message.error(res.msg);
        }
      });
  },
  methods: {
     getFileName(){
       this.downloadFileName ={}
      this.request.post("/download/getDownlaodName",{
           username:this.username,
           model_name:this.tableData.model_name,
      }).then((res)=>{
        console.log("获取的代码和附件的名称：",res);
        if(res.code_name!==null){
          this.downloadFileName = res
        }else{
          console.log("获取文件名称失败")
        }
      })

     },

    async download_code() {
      // this.getFileName()

      if(this.downloadFileName==={}){
        this.$message.error("文件为空")
        return
      }
      if(this.tableData.model_name==="单一容器基本模型"||this.tableData.model_name==="回转分区基本模型")
      {
        this.$message.warning("基本模型不能下载代码文件")
        return
      }
      console.log("获取模型姓名:\n");
      console.log(this.tableData.model_name);
      const formData = new FormData();
      formData.append("model_name", this.tableData.model_name);
      formData.append("username", this.username);
      const baseUrl = this.baseUrl;
      console.log(baseUrl);
      // 获取文件名
      let fileName = this.downloadFileName.code_name; // 默认文件名
      if(fileName === "null" ){
        this.$message.error("文件名为空，下载文件不存在")
        return
      }
      try {
        const response = await fetch("" + baseUrl + "/download/code", {
          method: "POST",
          body: formData,
        });

        if (response.ok) {

          const blob = await response.blob();
          const url = URL.createObjectURL(blob);
          const link = document.createElement("a");
          link.href = url;
          link.download = fileName;
          link.click();
        } else {
          this.$message.error(response.statusText)
          console.error("文件下载失败:", response.statusText);
          // 在这里添加下载失败的提示逻辑
        }
      } catch (error) {
        console.error("文件下载失败:", error);
        // 在这里添加下载失败的提示逻辑
      }
    },
    async download_attachment() {
      // this.getFileName()
      if(this.downloadFileName==={}){
        this.$message.error("文件为空")
        return
      }
      if(this.tableData.model_name==="单一容器基本模型"||this.tableData.model_name==="回转分区基本模型")
      {
        this.$message.warning("基本模型不能下载附件")
        return
      }
      console.log("获取模型姓名:\n");
      console.log(this.tableData.model_name);
      const formData = new FormData();
      formData.append("model_name", this.tableData.model_name);
      formData.append("username", this.username);
      const baseUrl = this.baseUrl;
      console.log(baseUrl);
      let fileName = this.downloadFileName.attachment_name; // 默认文件名
      if(fileName === "null" ){
        this.$message.error("文件名为空，下载文件不存在")
        return
      }
      try {
        const response = await fetch("" + baseUrl + "/download/attachment", {
          method: "POST",
          body: formData,
        });

        if (response.ok) {
          // 获取文件名


          const blob = await response.blob();
          const url = URL.createObjectURL(blob);
          const link = document.createElement("a");
          link.href = url;
          link.download = fileName;
          link.click();
        } else {
          this.$message.error(response.statusText)
          console.error("文件下载失败:", response.statusText);
          // 在这里添加下载失败的提示逻辑
        }
      } catch (error) {
        console.error("文件下载失败:", error);
        // 在这里添加下载失败的提示逻辑
      }
    },
    useParam() {
      let param = [];
      param.model_name = this.tableData.model_name;
      this.$emit("sethistoryparam", param);
      this.toPageCaculate();
    },
    toPageCaculate() {
      if (this.tableData.model_type === "单一容器") {
        this.$router.push("/1/S_C");
        this.$emit("addtab", {
          title: "单一容器", // 页面标题
          route: "/1/S_C", // 路由
          selected: true, // 设置选中状态
        });
      }
      if (this.tableData.model_type === "回转分区") {
        this.$router.push("/1/R_C");
        this.$emit("addtab", {
          title: "回转分区", // 页面标题
          route: "/1/R_C", // 路由
          selected: true, // 设置选中状态
        });
      }
    },
    load(callback) {
      console.log(
        JSON.stringify({
          username: this.username,
          model_name: this.tableData.model_name,
          page_num: 1,
          page_size: 2e6 + 10,
        }),
      );
      this.request
        .post("/model/hisCalList", {
          username: this.username,
          model_name: this.tableData.model_name,
          page_num: 1,
          page_size: 2e6 + 10,
        })
        .then((res) => {
          if (res.code === 200) {
            console.log("请求成功");
            console.log(res);
            this.historyCaculate = res.data;
            console.log("打印这个模型的历史计算\n" + this.historyCaculate);
            // this.historyCaculate = res.data.map(item => JSON.parse(item));
            console.log("打印处理过的历史计算\n" + this.historyCaculate);
          } else {
            // this.$message.error(this.res.msg)
            // console.log(this.res.msg)
          }
          if (callback) {
            callback();
          }
        });

    },

    //返回当前模型id的计算记录
    handleModelNameFilter() {
      let typeFilterdata = [...this.historyCaculate];
      //   typeFilterdata = typeFilterdata.filter(model => model.model_name === this.tableData.model_name&&);
      this.total = typeFilterdata.length;
      return typeFilterdata;
    },
    //返回当前页大小和页数的数据
    Show_CurrentPage(data) {
      // 计算起始索引
      const startIdx = (this.pageNum - 1) * this.pageSize;
      // 计算结束索引
      const endIdx = this.pageNum * this.pageSize - 1;
      const currentPageData = data.slice(startIdx, endIdx + 1);
      return currentPageData;
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.currentPageData = this.Show_CurrentPage(this.historyCaculate);

      // this.load()
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.currentPageData = this.Show_CurrentPage(this.historyCaculate);

      // this.load()
    },
    goBack() {
      // 使用Vue Router的go(-1)方法返回前一个历史记录
      // router.go(-1);
      this.$router.push("/1/m_l");
      this.$emit("addtab", {
        title: "模型列表", // 页面标题
        route: "/1/m_l", // 路由
        selected: true, // 设置选中状态
      });
    },
    handleEdit(row) {
      this.form = Object.assign({}, row);
      // this.$emit("addtab",{title:"ID-"+row.ID+"的计算详情",route:"/1/c_h_d",selected:true})
      this.$emit("addtab", {
        title: "计算详情",
        route: "/1/c_h_d",
        selected: true,
      });
      this.$emit("selectedcalculate", this.form);
      router.push({ path: "/1/c_h_d" });
      // this.$emit("sign",row)
    },
    // 展示确定删除的弹窗
    showDeleteDialog(id) {
      this.deleteDialogVisible = true;
      this.deleteid = id;
    },
    handleDelete() {
      if (this.deleteid !== "") {
        this.request
            .post("/cal/delCalByid", {
              id: this.deleteid,
              username: this.username,
            })
            .then((res) => {
              if (res.code === 200) {
                // this.$message.success(res.msg);
                this.$message.success("删除成功");
                this.deleteDialogVisible = false;
                this.load(() => {
                  this.historyCaculate = this.handleModelNameFilter();
                  this.currentPageData = this.Show_CurrentPage(this.historyCaculate);
                });
              } else {
                this.$message.error(res.msg);
              }
            });
        this.deleteid = "";
      } else {
        this.$message.error("删除的id不存在");
      }
    },
    // 取消显示确定删除的弹窗
    cancelDelete() {
      this.deleteDialogVisible = false;
    },
    transformData(data) {
      const transformed = [];

      // 确保将你的字典数据存储在变量 data 中
      const item = data;

      transformed.push(
        {
          fieldName: "模型名称",
          fieldValue: item.model_name,
        },
        {
          fieldName: "模型类型",
          fieldValue: item.model_type,
        },
        // Add more rows for other properties
        // ...
      );

      const subTableData = item.model_ParaIntro.map((param) => ({
        param_name: param.param_name,
        param_defaultValue: param.param_defaultValue,
      }));

      transformed.push({
        // fieldName: '参数信息',
        fieldName: "参数和默认值",
        fieldValue: subTableData,
      });

      return transformed;
    },
    sanitize(html) {
      const element = document.createElement("div");
      element.innerHTML = html;
      return element.innerText;
    },
  },
};
</script>

<style lang="scss" scoped>
.footpage {
  /*padding: 0.625em 0;*/
  font-size: 0.938em;
  display: flex;
  align-items: center;
  align-content: center;
  justify-content: center;
}

.total {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  overflow: auto;
  padding-bottom: 100px;
  padding: 20px;

  //background-color: #F9F7F7;
  //background-color: rgb(255,255,255,0.1);
}

.spss {
}
.backbutton {
  width: 80px;
  height: 30px;
  font-size: 15px;
  margin-top: 0;
  margin-bottom: 5px;
  border: 1.2px solid #409eff;
}

.functionbutton {
  //margin-top: 5%;
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin: 50px;
  button {
    border-radius: 4px;
    width: 80px;
    height: 30px;
    border: 1.2px solid #409eff;
  }
}

/*标题小矩形*/
.blue-rectangle {
  width: 10px;
  height: 30px;
  //background-color: #3f72af;
  background-color: #409eff;
  margin-right: 10px;
}
.tablespace {
  /*margin-left: 20px;*/
  /*margin-top: 10px;*/
  width: 100%;
  margin-bottom: 10px;
  display: flex;
  flex-direction: row;
  //justify-content: center;
  align-content: center;
}
.processcontent {
  margin-left: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  width: 90%;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-content: center;
}

.up2hv2img {
  background-color: white;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 40%;

  margin-top: 20px;
  border-right: 1px solid #dcdfe6;
  border-bottom: 1px solid #dcdfe6;
  border-top: 1px solid #dcdfe6;
  /*background-color: transparent;*/
}

.table1 {
  width: 60%;
  //width: 500px;
  margin-top: 20px;
  //border-right: 1px solid #DCDFE6;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  //background-color: white;
}
.table2 {
  width: 100%;
  /*margin-top: 20px;*/
}

.stepscontent {
  margin-left: 20px;
  margin-top: 30px;
  margin-bottom: 10px;
  display: flex;
  flex-direction: row;
  width: 90%;
  //div:last-child {
  //  width: 100%;
  //  padding: 10px 10px 60px 10px;
  //  background-color: white;
  //  border: 1px solid #dcdfe6;
  //  border-radius: 4px;
  //}

  padding: 10px 10px 30px 20px;
  background-color: white;
  //border: 1px solid #dcdfe6;
  border-radius: 4px;
  div {
    div {
      font-weight: 500;
      font-size: 14px;
    }
    div:not(:last-child) {
      margin-bottom: 20px;
    }
  }
}

.conclusioncontent {
  width: 90%;
  margin-left: 20px;
  margin-top: 40px;
  margin-bottom: 10px;
}

.totaltitle {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-top: 10px;
  margin-bottom: 10px;
}

.totaltitle1 {
  margin-top: 60px;
}

.title_1 {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 10px;
}

.title_1 > img {
  width: 30px;
  margin-right: 10px;
}

.titled2 > h1 {
  margin-bottom: 10px;
}
.datafilename {
  margin-left: 10px;
  color: blue;
  text-decoration: underline;
}
.algorithmconfigure {
  margin-left: 10px;
}
.analyzeresults {
  margin-left: 40px;
}
.arrow {
  display: flex;
  flex-direction: row;
}
.arrow > img {
  text-align: left;
  width: 30px;
}

.sequencechart {
  display: flex;
  margin-left: 20px;

  justify-content: center;
  margin-top: 10px;

  div:not(:last-child) {
    background-color: white;
    border-radius: 4px;
  }
}

.attached_file {
  margin-top: 30px;
}
/*附件下载区样式*/
.attachment {
  display: flex;
  flex-direction: row;
}

.downloadcode {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.downloadattachment {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.atimg {
  width: 100px;
  height: 100px;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}
.atimg > img {
  width: 90%;
}

.tablebutton {
  border: 1.2px solid #409eff;
}
</style>
